package com.magic.item.controller;

import com.github.pagehelper.PageInfo;
import com.magic.item.pojo.User;
import com.magic.item.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lan.jianyuan
 * @create 2021-03-24-15:44
 */
@Controller
public class UsersController {
    @Autowired
    private UserService userService;
    @RequestMapping("user/page")
    public ResponseEntity<PageInfo<User>> getPageInfo(
            @RequestParam(value = "keyword", defaultValue = "") String keyword,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize
    ) {
        PageInfo<User> pageInfo = userService.getPageInfo(keyword, pageNum, pageSize);
        if (pageInfo == null || CollectionUtils.isEmpty(pageInfo.getList())) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(pageInfo);
    }
    @RequestMapping("user/delete")
    public ResponseEntity<Void> deleteUser(@RequestParam(value = "uid", required = false)Long uid) {
        userService.deleteUser(uid);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    @GetMapping("user/{uid}")
    public ResponseEntity<List<User>> queryUserByUid(@PathVariable("uid")Long uid) {
        if (uid == null || uid < 0) {
            // pid为null或者小于等于0，响应400 : 参数不合法
            return ResponseEntity.badRequest().build();
        }
        // 执行查询操作
        List<User> userList = this.userService.queryUserById(uid);
        if (CollectionUtils.isEmpty(userList)) {
            return ResponseEntity.notFound().build();
        }
        // 响应200
        return ResponseEntity.ok(userList);
    }
    @PutMapping("user/update")
    public ResponseEntity<Void> updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
}
